package com.mnb.base.service.impl;

import com.mnb.base.entity.StPptnR;
import com.mnb.base.mapper.StPptnRMapper;
import com.mnb.base.mapper.StStbprpBMapper;
import com.mnb.base.service.StRiverRService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Service
public class RainfallCalculationService {

    private static final Logger logger = LoggerFactory.getLogger(RainfallCalculationService.class);
    private static final LocalTime EXECUTION_TIME = LocalTime.of(8, 0); // 8:00 AM

    @Autowired
    private StPptnRMapper stPptnRRepository;

    @Autowired
    private StStbprpBMapper stStbprpBRepository;;

    /**
     * 计算指定日期的日降雨量并更新DYP字段
     * 计算范围：前一天8点到当天8点
     */
    @Transactional
    public void calculateDailyRainfall(LocalDate targetDate) {
        logger.info("开始计算 {} 的日降雨量", targetDate);

        // 计算时间范围：前一天8点到当天8点
        LocalDateTime startTime = targetDate.minusDays(1).atTime(EXECUTION_TIME);
        LocalDateTime endTime = targetDate.atTime(EXECUTION_TIME);
        LocalDateTime storageTime = targetDate.atTime(EXECUTION_TIME);

        logger.info("计算时间范围: {} 到 {}", startTime, endTime);
        logger.info("存储时间: {}", storageTime);

        // 获取所有站点
        List<String> stcds = stStbprpBRepository.findAllStationCodes();
        logger.info("找到 {} 个站点", stcds.size());

        int processedCount = 0;
        int successCount = 0;

        for (String stcd : stcds) {
            try {
                processedCount++;
                boolean success = calculateDailyRainfallForStation(stcd, startTime, endTime, storageTime);
                if (success) {
                    successCount++;
                }
            } catch (Exception e) {
                logger.error("处理站点 {} 时发生错误: {}", stcd, e.getMessage(), e);
            }
        }

        logger.info("日降雨量计算完成. 处理站点: {}, 成功: {}", processedCount, successCount);
    }

    /**
     * 为指定站点计算日降雨量
     */
    @Transactional
    public boolean calculateDailyRainfallForStation(String stcd,
                                                    LocalDateTime startTime,
                                                    LocalDateTime endTime,
                                                    LocalDateTime storageTime) {
        try {
            // 计算DRP总和
            BigDecimal totalDrp = stPptnRRepository.calculateDailyRainfall(stcd, startTime, endTime);

            logger.info("站点 {} 在 {} 到 {} 期间的DRP总和: {}",
                    stcd, startTime, endTime, totalDrp);

            // 检查是否已存在DYP记录
            StPptnR existingRecord = stPptnRRepository.selectByPrimaryKey(stcd, java.sql.Timestamp.valueOf(storageTime));

            if(totalDrp == null){
                //说明肯本没有数据 不处理
                logger.info("站点 {} 的DYP记录: {} 无数据！", stcd, totalDrp);
                return true;
            }
            if (existingRecord != null) {
                // 更新现有记录
                stPptnRRepository.updateDyp(stcd,java.sql.Timestamp.valueOf(storageTime), totalDrp);
                logger.info("更新站点 {} 的DYP记录: {}", stcd, totalDrp);
            } else {
                // 创建新记录
                existingRecord.setStcd(stcd);
                existingRecord.setTm(java.sql.Timestamp.valueOf(storageTime));
                existingRecord.setDyp(totalDrp);
                stPptnRRepository.insert(existingRecord);
                logger.info("创建站点 {} 的新DYP记录: {}", stcd, totalDrp);
            }

            return true;
        } catch (Exception e) {
            logger.error("计算站点 {} 的日降雨量时发生错误: {}", stcd, e.getMessage(), e);
            return false;
        }
    }


    /**
     * 手动触发日降雨量计算（用于测试或手动执行）
     */
    @Transactional
    public void manualCalculateDailyRainfall(LocalDate targetDate) {
        logger.info("手动触发日降雨量计算，目标日期: {}", targetDate);
        calculateDailyRainfall(targetDate);
    }

}
